import { existsSync } from "fs";
import { Environment } from "./core/Environment";
import { Handler } from "./core/Handler";
import { join, parse } from "path";
import { SyncData, SyncType } from "./core/Defines";
import * as Assets from "./core/AssetsHelper";
import * as FixEngine from "./fix_engine/Helper";
import * as TinifyCompress from "./tinify-compress/Helper";

export class Helper extends Handler {
    private static _instance: Helper = null!;
    static get instance() {
        return this._instance || (this._instance = new Helper);
    }

    /**@description Bunldes 地址 */
    public readonly bundlesUrl = Environment.publicBundlesUrl;

    private _fixEngine = new FixEngine.default();
    private _assets = new Assets.default();

    private _tinifyCompress = new TinifyCompress.default();

    /**@description 获得当前工程的当前分支 */
    public async gitCurBranch() {
        this.chdir(this.projPath);
        this.log(`检查当前分支`, false);
        let result = await this.exec("git branch");
        this.log(`检查当前分支`, true);
        if (result.isSuccess) {
            let arr = result.data.split("\n");
            for (let i = 0; i < arr.length; i++) {
                let branch = arr[i];
                if (branch.indexOf("*") == 0) {
                    return branch.replace("*", "").trim();
                }
            }
        }
        return null;
    }

    /**
     * @description 拉取Bundles代码
     * @param savePath 保存目录名
     * @param url 项目地址
     * @returns
     */
    public async gitPull(savePath: string, url: string) {
        let name = parse(savePath).name;
        this.log(`拉取远程 : ${name}`, false);
        let branch = await this.gitCurBranch();
        if (existsSync(savePath)) {
            // 已经存在，转到目录，更新git pull,切分支
            this.logger.log(`已经存在 : ${savePath}`);
            this.chdir(savePath);
            let result = await this.exec(`git pull`);
            this.logger.log(`正在更新 : ${name}`);
            if (!result.isSuccess) {
                return;
            }
            result = await this.exec(`git checkout ${branch}`);
            if (result.isSuccess) {
                this.logger.log(`${name} 成功切换分支 : ${branch}`);
            }
        } else {
            // 不存在，转到工程目录, 拉取远程git clone, 转到目录, 切分支
            this.logger.log(`不存在 : ${savePath}`);
            this.chdir(this.projPath);
            this.logger.log(`拉取远程 : ${name}`);
            let result = await this.exec(`git clone ${url} ${name}`);
            if (!result.isSuccess) {
                return;
            }
            this.logger.log(`拉取成功 : ${name}`);
            this.chdir(savePath);
            result = await this.exec(`git checkout ${branch}`);
            if (result.isSuccess) {
                this.logger.log(`${name} 成功切换分支 : ${branch}`);
            }
        }
        this.log(`拉取远程 : ${name}`, true);
    }

    /**@description 链接 */
    async symlinkSync(datas: SyncData[], tag: string, fromRoot: string = null!, toRoot: string = null!) {
        this.log(`链接${tag}`, false);
        if (!fromRoot) {
            fromRoot = this.projPath;
        }
        if (!toRoot) {
            toRoot = this.projPath;
        }
        let fromPath: string = "";
        let toPath: string = "";
        for(let i = 0; i < datas.length; i++) {
            let data: SyncData = datas[i];
            switch(data.type) {
                case SyncType.CUR_ALL_FILES:
                    {
                        fromPath = join(fromRoot, data.from);
                        
                    }
                    break;
            }
        }
    }

    async getAssets() {
        this.logger.log(`获取资源信息`);
        // await this._assets.getAssets();
    }

    async fixEngine() {
        this.log(`引擎修正`, false);
        await this._fixEngine.run();
        this.log(`引擎修正`, true);
    }

    async tinifyCompress() {
        this.log(`Tinypng 压缩`, false);
        await this._tinifyCompress.validateAndCompress();
        this.log(`Tinypng 压缩`, true);
    }
}